function V = patch2vecs(M, psiz, intvs)
% Generate patch vectors
%   
%   V = patch2vecs(M, psiz, intvs)
%

% Created by Dahua Lin, on Mar 8, 2012
%

%% verify input arguments

if ~(isnumeric(M) && isreal(M) && ~issparse(M) && ndims(M) == 2)
    error('localhists:invalidarg', 'M should be a two-dimensional matrix.');
end

%% main

if isscalar(psiz)
    ph = psiz;
    pw = psiz;
else
    ph = psiz(1);
    pw = psiz(2);
end

if isscalar(intvs)    
    yintv = intvs;
    xintv = intvs;
else
    yintv = intvs(1);
    xintv = intvs(2);
end


[h, w] = size(M);
h2 = h - ph + 1;
w2 = w - pw + 1;

xs = 1:xintv:w2;
ys = 1:yintv:h2;

[x, y] = meshgrid(xs, ys);

[ox, oy] = meshgrid(0:pw-1, 0:ph-1);

X = bsxfun(@plus, reshape(x, 1, []), ox(:));
Y = bsxfun(@plus, reshape(y, 1, []), oy(:));

V = M(Y + h * (X - 1));
V = reshape(V, [ph * pw, size(x)]);

